<template>
  <div>
    <h3>权限管理组件</h3>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 角色列表区域 -->
    <!-- row-key="id" 是2019年3月提供的新特性，
if there's nested data, rowKey is required.
如果这是一个嵌套的数据，rowkey 是必须添加的属性 -->
    <el-card>
      <el-button type="primary" plain class="addroles" @click="addRoles">添加角色</el-button>
      <el-table :row-key="roleList.id" :data="roleList" border>
        <!-- 添加展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 栅格系统 -->
            <el-row :class="['bdbottom', index === 0 ? 'bdtop' : '', 'vcenter']" v-for="(item, index) in scope.row.children" :key="item.id">
              <!-- 渲染一级 -->
              <!-- 第1列 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item.id, scope.row)">{{ item.authName }}-{{ index + 1 }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级三级 -->
              <!-- 第2列 -->
              <el-col :span="19">
                <el-row :span="5" v-for="(subitem, index2) in item.children" :key="subitem.id" :class="{ bdtop: index2 !== 0, vcenter: true }">
                  <!-- 2级 -->
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightById(scope.row, subitem.id, item)">{{ subitem.authName }}-{{ index2 + 1 }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <!-- 3级 -->
                    <el-tag v-for="(lastitem, index3) in subitem.children" :key="lastitem.id" type="warning" closable @close="removeRightById(scope.row, lastitem.id, subitem)"
                      >{{ lastitem.authName }}-{{ index3 + 1 }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <h1 v-if="scope.row.children.length == 0">---垃圾，别看了，你媚权限---</h1>
            <!-- <pre>
            {{ scope.row.children }}
            </pre> -->
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="editRolesinfo(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteRightDialog(scope.row)">删除</el-button>
            <el-button size="mini" type="warning" icon="el-icon-setting" @click="showSerRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限 -->
    <el-dialog title="权限分配" :visible.sync="dialogShow" width="50%">
      <!-- 树形结构 -->
      <el-tree :data="rightsList" show-checkbox :props="treeProps" default-expand-all node-key="id" :default-checked-keys="defKeys" ref="treeRef"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogShow = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色 -->
    <el-dialog title="编辑角色" :visible.sync="rolesIsShow" width="50%" @close="closeEditRoles">
      <el-form :model="editRoles" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoles.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoles.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rolesIsShow = false">取 消</el-button>
        <el-button type="primary" @click="sureEditRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色 -->
    <el-dialog title="添加角色" :visible.sync="addRolesIsShow" width="50%" @close="closeAddRoles">
      <el-form :model="AddRoles" :rules="rules" ref="AddruleForm" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="AddRoles.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="AddRoles.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesIsShow = false">取 消</el-button>
        <el-button type="primary" @click="sureAddRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Roles',
  data() {
    return {
      roleList: [],
      // 分配权限弹出框
      dialogShow: false,
      rightsList: [],
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中节点Id值
      defKeys: [],
      // 选中角色ID
      rightsId: '',
      // 编辑角色弹出框
      rolesIsShow: false,
      // 编辑弹出框内容
      editRoles: {
        roleName: '',
        roleDesc: ''
      },
      // 编辑ID
      editId: -1,
      // 编辑规则
      rules: {
        roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
        roleDesc: [{ required: true, message: '请输入角色描述', trigger: 'blur' }]
      },
      // 新增弹出框
      addRolesIsShow: false,
      // 新增弹出框内容
      AddRoles: {
        roleName: '',
        roleDesc: ''
      }
    }
  },
  created() {
    this.getRoleList()
    // this.getightsList()
  },
  methods: {
    // 获取角色权限数据
    async getRoleList() {
      const { data: res } = await this.$axios.get('roles')
      // 如果返回状态为异常状态则报错并返回
      if (res.meta.status !== 200) return this.$message.error('角色列表' + res.meta.msg)
      // //如果返回状态正常，将请求的数据保存在data中
      // this.roleList = res.data
      this.roleList = res.data
    },
    // 移除权限函数
    removeRightById(role, rightId, father) {
      // 确认删除提示
      this.$messagebox.confirm('确认删除吗？', '来自你爹的提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        callback: async (action) => {
          // 回调函数中，如果点击确认，参数为confirm
          // 回调函数中，如果点击取消，参数为cancel
          if (action === 'confirm') {
            const { data: res } = await this.$axios.delete(`roles/${role.id}/rights/${rightId}`)
            if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
            // 成功提示
            this.$message.success(res.meta.msg)
            // 返回删除权限之后的列表数据，无需重新拿取全部数据---方法1（需要后端配合，重新刷新整个权限列表，性能较低）
            // role.children = res.data
            // 前端单方面删除局部渲染数组---方法2（前端方面删除，只删除改变项，性能较高）
            const targetIndex = father.children.findIndex((e) => e.id === rightId)
            targetIndex > -1 && father.children.splice(targetIndex, 1)
          } else {
            this.$message.info('取消删除')
          }
        }
      })
    },
    // 点击分配权限按钮
    showSerRightDialog(role) {
      this.rightsId = role.id
      this.dialogShow = true
      this.getightsList()
      this.defKeys = []
      this.getLeafKeys(role, this.defKeys)
    },
    // 权限处理函数
    async getightsList() {
      const { data: res } = await this.$axios.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取权限列表失败')
      this.rightsList = res.data
    },

    // 通过递归获取角色的三级权限的ID
    getLeafKeys(node, arr) {
      // 该函数会获取到当前角色的所有三级权限id并添加到defKeys中
      // 如果当前节点不包含children属性，则表示node为三级权限
      if (!node.children) {
        arr.push(node.id)
      } else {
        // 递归调用
        node.children.forEach((item) => this.getLeafKeys(item, arr))
      }
      // !node.children ? !arr.push(node.id) : true && node.children.forEach((item) => this.getLeafKeys(item, arr))
    },
    async allotRights() {
      let keys = [
        // 拿到选中和半选中的ID
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      keys = keys.join(',')
      const { data: res } = await this.$axios({
        url: `roles/${this.rightsId}/rights`,
        method: 'POST',
        data: { rids: keys }
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.dialogShow = false
      this.getRoleList()
    },
    // 编辑角色
    editRolesinfo(val) {
      this.rolesIsShow = true
      this.editRoles.roleName = val.roleName
      this.editRoles.roleDesc = val.roleDesc
      this.editId = val.id
    },
    // 关闭编辑弹出层
    closeEditRoles() {
      this.$refs.ruleForm.resetFields()
    },
    // 关闭新增弹出层
    closeAddRoles() {
      this.$refs.AddruleForm.resetFields()
    },
    // 点击确定
    sureEditRoles() {
      this.$refs.ruleForm.validate(async (val) => {
        if (!val) return this.$message.error('想清楚再确定')
        const { data: res } = await this.$axios({
          url: `roles/${this.editId}`,
          method: 'PUT',
          data: this.editRoles
        })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success('修改成功')
        this.getRoleList()
        this.rolesIsShow = false
      })
    },
    // 添加角色
    addRoles() {
      this.addRolesIsShow = true
    },
    // 点击确定
    sureAddRoles() {
      this.$refs.AddruleForm.validate(async (val) => {
        if (!val) return this.$message.error('想清楚再新增')
        const { data: res } = await this.$axios({
          url: 'roles',
          method: 'POST',
          data: this.AddRoles
        })
        console.log(res)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getRoleList()
        this.addRolesIsShow = false
      })
    },
    // 删除角色
    async deleteRightDialog(val) {
      try {
        await this.$messagebox.confirm('确认删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        // 点击确定做的事情
        const { data: res } = await this.$axios.delete(`roles/${val.id}`)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getRoleList()
      } catch (error) {
        //   点击取消做的事情
      }
    }
  }
}
</script>

<style>
.el-tag {
  margin: 7px;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.bdtop {
  border-top: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
.addroles {
  margin-bottom: 15px;
}
</style>
